<script setup>
import {onMounted, ref, watch, computed} from 'vue'
import { Plus } from '@element-plus/icons-vue'
import axios from "axios";
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import {ElMessage} from "element-plus";
import {router} from "@/router/index.js";
import {useRoute} from "vue-router";

const route = useRoute()
const localGoodsData = (id) =>{
  if(id){
    axios.get(`/goods/selectGoodsById/${id}`).then(resp=>{
      productForm.value = {
        ...resp.data,
        photos: Array.isArray(resp.data.photos)
            ? resp.data.photos
            : JSON.parse(resp.data.photos || '[]')
      }
    })
  }
}
const id = ref(route.query.id);
watch(() => route.query.id, (newValue) => {
  id.value = newValue
  localGoodsData(newValue)
})
const productForm = ref({
  name: '',           // 商品名称
  title: '',          // 商品标题
  subtitle: '',       // 副标题
  category: '',       // 主分类
  subCategory: '',    // 子分类
  sequence: 1,        // 排序
  goodsNum: '',       // 商品编码
  image: '',          // 主图地址
  mainImage: '',      // 当前主图（可选）
  price: 0,           // 商品价格
  originalPrice: 0,   // 原价
  inventory: 0,       // 库存
  inventoryWarn: 0,   // 预警库存
  photos: []          // 👈👈 关键：商品相册必须初始化为空数组！
});

// 计算页面标题
const pageTitle = computed(() => {
  return isLook.value ? '商品详情' : id.value ? '编辑商品' : '添加商品'
})

const categoryOptions = ref([])
const subCategoriesOptions = ref([])


const imageUrl = ref('')

//当上传文件成功后触发  钩子函数/回调函数
const handleAvatarSuccess = (
    resp,
    uploadFile
) => {
  imageUrl.value = resp;
  productForm.value.image = imageUrl.value;

}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('您上传的头像必须是jpg或者png格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('您上传的图片大小必须2M以内')
    return false
  }
  return true
}
const handleReplaceImage = () => {
  productForm.value.image = '';
};
const getCategory = ()=>{
  axios.get(`/category/getCategoryName`).then(resp=>{

    categoryOptions.value = resp.data
  });
}

const getSubByCategory = (categoryCode)=>{
  axios.get(`/category/getSubByCategory/${categoryCode}`).then(resp=>{
    subCategoriesOptions.value = resp.data
  });
}

const handleCategoryChange = (categoryCode) => {
  if(categoryCode){
    getSubByCategory(categoryCode);
  } else {
    subCategoriesOptions.value = []; // 清空子分类选项
  }
}

// 设置主图
const setMainImage = (imageUrl) => {
  productForm.value.mainImage = imageUrl;
  ElMessage.success('主图设置成功');
}
// 删除图片
const removeImage = async (index) => {
  try {
    if (index < 0 || index >= productForm.value.photos.length) {
      throw new Error('无效的图片索引');
    }

    const imageUrl = productForm.value.photos[index];
    if (!imageUrl) {
      throw new Error('图片URL无效');
    }

    // 提取文件名（兼容非标准URL）
    let fileName;
    if (imageUrl.startsWith('http')) {
      fileName = imageUrl.split('/').pop();
    } else {
      fileName = `image_${Date.now()}.jpg`;
    }

    // 先删除前端数据
    productForm.value.photos.splice(index, 1);

    // 检查并清除主图
    if (productForm.value.mainImage === imageUrl) {
      productForm.value.mainImage = '';
    }

    // 尝试调用删除接口（可选）
    try {
      await axios.delete(`/api/delete/${fileName}`);
      ElMessage.success('图片删除成功');
    } catch (serverError) {
      console.warn('服务器删除失败（不影响前端）:', serverError);
    }

  } catch (error) {
    console.error('删除过程中出错:', error);
    ElMessage.error(error.message || '图片删除失败');
  }
};


const editorOptions = {
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'], // 加粗、斜体、下划线、删除线
      ['blockquote', 'code-block'], // 引用、代码块
      [{ 'header': 1 }, { 'header': 2 }], // 标题1、标题2
      [{ 'list': 'ordered'}, { 'list': 'bullet' }], // 有序列表、无序列表
      [{ 'script': 'sub'}, { 'script': 'super' }], // 下标、上标
      [{ 'indent': '-1'}, { 'indent': '+1' }], // 缩进
      [{ 'direction': 'rtl' }], // 文本方向
      [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 标题级别
      [{ 'color': [] }, { 'background': [] }], // 字体颜色、背景色
      [{ 'font': [] }], // 字体
      [{ 'align': [] }], // 对齐方式
      ['clean'], // 清除格式
      ['link', 'image', 'video'] // 链接、图片、视频
    ]
  },
  placeholder: '请输入商品详情内容...',
  theme: 'snow'
};
const handleGalleryUpload = async (file) => {
  try {
    const formData = new FormData();
    formData.append('file', file.raw);

    // 上传图片到服务器
    const response = await axios.post('/api/upload', formData);
    const imageUrl = response.data; // 获取服务器返回的图片URL

    // 将新图片添加到相册
    productForm.value.photos.push(imageUrl);

    ElMessage.success('图片上传成功');
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('图片上传失败');
  }
}




const submitForm = () => {
  if(id){
    axios.put(`/goods/updateGoodsById/${id.value}`,productForm.value).then(resp=>{
      router.back()
      ElMessage.success(resp.data);
    })
  }else {
    axios.post(`/goods/addGoods`,productForm.value).then(resp=>{
      router.back()
      ElMessage.success(resp.data)
    })
  }
}

const cancel = () => {
  router.back()
}

onMounted(()=>{
  localGoodsData(id.value);
  getCategory();
})
</script>

<template>
  <div class="add-product-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb separator="/" class="custom-breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/product' }">商城系统</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/product/list' }">商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 页面标题 -->
      <h2 class="page-title">添加商品</h2>

    </div>


    <!-- 表单区域 -->
    <div class="form-container">
      <h3 class="form-section-title">基本信息</h3>

      <el-form :model="productForm" label-width="100px" class="product-form">
        <el-form-item label="商品名称：" class="form-item-custom">
          <el-input v-model="productForm.name" placeholder="请输入商品名称" class="custom-input" />
        </el-form-item>

        <el-form-item label="商品标题：" class="form-item-custom">
          <el-input v-model="productForm.title" placeholder="请输入商品标题" class="custom-input" />
        </el-form-item>

        <el-form-item label="商品副标题：" class="form-item-custom">
          <el-input v-model="productForm.subtitle" placeholder="选填" class="custom-input" />
          <span class="form-tip">（选填）</span>
        </el-form-item>

        <div class="form-section">
          <el-form-item label="商品分类：" class="form-item-custom category-form-item">
            <div class="category-select-group">
              <el-select
                  v-model="productForm.category"
                  @change="handleCategoryChange"
                  class="category-select"
                  placeholder="请选择主分类"
              >
                <el-option
                    v-for="(item, index) in categoryOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                />
              </el-select>

              <el-select
                  v-model="productForm.subCategory"
                  :disabled="!productForm.category"
                  placeholder="请选择子分类"
                  class="subcategory-select"
              >
                <el-option
                    v-for="(item, index) in subCategoriesOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </div>
          </el-form-item>
        </div>


        <el-form-item label="商品顺序：" class="form-item-custom">
          <el-input-number v-model="productForm.sequence" :min="1" class="custom-input-number" />
          <span class="form-tip">数字小则靠前展示</span>
        </el-form-item>

        <el-form-item label="商品编码：" class="form-item-custom">
          <el-input v-model="productForm.goodsNum" placeholder="请输入商品编码" class="custom-input" />
        </el-form-item>

        <el-form-item label="商品图片" prop="image">
          <div class="image-upload-container">
            <div class="image-preview-wrapper">
              <!-- 图片预览 -->
              <div class="image-preview" v-if="productForm.image">
                <el-image
                    :src="productForm.image"
                    fit="cover"
                    class="product-image"
                    :preview-src-list="[productForm.image]"
                />
                <div class="image-actions">
                  <el-button
                      size="small"
                      type="primary"
                      @click="handleReplaceImage"
                  >
                    替换
                  </el-button>
                </div>
              </div>

              <!-- 上传组件 -->
              <el-upload
                  v-if="!productForm.image"
                  action="http://localhost:8080/api/upload"
                  list-type="picture-card"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :auto-upload="true"
                  :show-file-list="false"
                  class="product-uploader"
              >
                <el-icon><Plus /></el-icon>
                <div class="upload-tip">点击上传图片</div>
              </el-upload>
            </div>

            <div class="upload-tips">
              <p>建议尺寸：800×800像素</p>
              <p>支持格式：JPG、PNG</p>
              <p>大小不超过2MB</p>
            </div>
          </div>
        </el-form-item>



        <h3 class="form-section-title">价格与库存</h3>

        <el-form-item label="商品价格：" class="form-item-custom">
          <el-input-number v-model="productForm.price" :min="0" :precision="2" class="custom-input-number" />
          <span class="form-unit">元</span>
        </el-form-item>

        <el-form-item label="商品原价：" class="form-item-custom">
          <el-input-number v-model="productForm.originalPrice" :min="0" :precision="2" class="custom-input-number" />
          <span class="form-tip">（选填）</span>
          <span class="form-unit">元</span>
        </el-form-item>

        <el-form-item label="商品库存：" class="form-item-custom">
          <el-input-number v-model="productForm.inventory" :min="0" class="custom-input-number" />
          <span class="form-unit">件</span>
        </el-form-item>

        <el-form-item label="库存预警：" class="form-item-custom">
          <el-input-number v-model="productForm.inventoryWarn" :min="0" class="custom-input-number" />
          <span class="form-unit">件</span>
        </el-form-item>

        <!-- 商品相册 -->
        <h3 class="form-section-title">商品相册</h3>
        <div class="image-gallery">
          <div v-for="(image, index) in productForm.photos" :key="index" class="image-item">
            <el-image :src="image" fit="cover" class="gallery-image" />
            <div class="image-actions">
              <el-button
                  size="small"
                  type="primary"
                  @click="setMainImage(image)"
                  :disabled="productForm.mainImage === image"
              >
                {{ productForm.mainImage === image ? '当前主图' : '设为主图' }}
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="removeImage(index)"
              >
                删除图片
              </el-button>
            </div>
          </div>

          <!-- 上传组件 -->
          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleGalleryUpload"
              :show-file-list="false"
              class="gallery-upload"
              accept="image/jpeg,image/png"
              :before-upload="beforeAvatarUpload"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>

        <!-- 主图展示部分 -->
        <el-form-item label="商品主图" prop="mainImage" v-if="productForm.mainImage">
          <div class="main-image-preview">
            <el-image
                :src="productForm.mainImage"
                fit="cover"
                class="main-image"
                :preview-src-list="[productForm.mainImage]"
            />
            <div class="main-image-tip">当前主图</div>
          </div>
        </el-form-item>

        <!-- 商品详情 -->
        <h3 class="form-section-title">商品详情</h3>
        <el-form-item label="商品详情：" class="form-item-custom">
          <div class="detail-tip">将商品的介绍与特殊说明可以编写在详情中</div>
        </el-form-item>

        <el-tabs type="border-card" class="detail-tabs">
          <el-tab-pane label="电脑端详情">
            <quill-editor
                v-model:content="productForm.descriptionPc"
                content-type="html"
                :options="editorOptions"
                class="detail-editor"
                :read-only="isLook"
            />
          </el-tab-pane>
          <el-tab-pane label="移动端详情">
            <quill-editor
                v-model:content="productForm.descriptionMobile"
                content-type="html"
                :options="editorOptions"
                class="detail-editor"
            />
          </el-tab-pane>
        </el-tabs>

        <!-- 表单操作按钮 -->
        <el-form-item class="form-actions" v-if="!isLook">
          <el-button type="primary" class="submit-btn" @click="submitForm">保存</el-button>
          <el-button class="cancel-btn" @click="cancel">取消</el-button>
        </el-form-item>
        <el-form-item class="form-actions" v-else>
          <el-button type="primary" class="submit-btn" @click="router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.add-product-container {
  padding: 20px 30px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.breadcrumb-container {
  padding: 15px 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.custom-breadcrumb {
  font-size: 14px;
}

.page-title {
  margin: 20px 0;
  font-size: 20px;
  font-weight: 500;
  color: #333;
}

.form-container {
  background-color: #fff;
  padding: 20px 25px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.form-section-title {
  margin: 0 0 20px 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.product-form {
  margin-top: 15px;
}

.form-item-custom {
  margin-bottom: 22px;
}

.form-item-custom :deep(.el-form-item__label) {
  color: #606266;
  font-weight: normal;
  padding-right: 10px;
  text-align: left;
}

.custom-input {
  width: 400px;
}

.custom-input :deep(.el-input__inner) {
  height: 36px;
  line-height: 36px;
}

.custom-cascader {
  width: 400px;
}

.custom-input-number {
  margin-right: 10px;
}

.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 13px;
  line-height: 1.5;
}

.upload-area {
  display: flex;
  align-items: flex-start;
}

.custom-upload :deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-tip {
  margin-left: 15px;
  color: #909399;
  font-size: 13px;
  line-height: 1.5;
}

.form-actions {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.submit-btn {
  width: 100px;
  height: 36px;
}

.cancel-btn {
  width: 100px;
  height: 36px;
  margin-left: 15px;
}

.category-form-item :deep(.el-form-item__content) {
  display: flex;
  line-height: normal;
}

.category-select-group {
  display: flex;
  width: 400px; /* 与其他输入框同宽 */
}

.category-select {
  flex: 1;
  margin-right: 10px;
}

.subcategory-select {
  flex: 1;
}

/* 调整下拉框内部输入框高度与其他输入框一致 */
.category-select :deep(.el-input__inner),
.subcategory-select :deep(.el-input__inner) {
  height: 36px;
  line-height: 36px;
}

.form-unit {
  margin-left: 10px;
  color: #606266;
}

/* 商品相册样式 */
.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.image-item {
  position: relative;
  width: 150px;
  height: 150px;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
}

.gallery-image {
  width: 100%;
  height: 100%;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  padding: 8px;
  display: flex;
  justify-content: space-around;
}

.gallery-upload :deep(.el-upload--picture-card) {
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-tip {
  color: #909399;
  font-size: 14px;
  margin-bottom: 15px;
}

.detail-tabs {
  margin-bottom: 30px;
}

.detail-editor {
  height: 500px;
  margin-bottom: 20px;
}

/* 调整富文本编辑器工具栏样式 */
:deep(.ql-toolbar) {
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  border: 1px solid #dcdfe6;
}

:deep(.ql-container) {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  border: 1px solid #dcdfe6;
  height: calc(100% - 42px);
}

/* 调整标签页样式 */
:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active) {
  background-color: #f5f7fa;
}

.image-upload-container {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.product-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 150px;
  height: 150px;
}

.product-image-uploader:hover {
  border-color: #409eff;
}

.upload-content {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8c939d;
  font-size: 14px;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  text-align: center;
  line-height: 1.5;
}

.upload-tips {
  color: #909399;
  font-size: 13px;
  line-height: 1.5;
  margin-top: 10px;
}

.upload-tips p {
  margin: 5px 0;
}
.image-upload-container {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

/* 图片预览区域 */
.image-preview-wrapper {
  position: relative;
}

.image-preview {
  width: 150px;
  height: 150px;
  border: 1px solid #eaeaea;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.image-preview:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

/* 图片操作按钮 */
.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7); /* 更深的背景，提高对比度 */
  padding: 8px;
  display: flex;
  justify-content: space-around;
  /* 移除 opacity: 0; */
  transition: opacity 0.3s;
}
.image-preview:hover .image-actions {
  opacity: 1;
}

/* 上传按钮样式 */
.product-uploader {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: border-color 0.3s;
  background-color: #fafafa;
}

.product-uploader:hover {
  border-color: #409eff;
}

.product-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.product-uploader .el-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 8px;
}

.upload-tip {
  color: #8c939d;
  font-size: 12px;
  text-align: center;
}

/* 上传提示文字 */
.upload-tips {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.upload-tips p {
  margin: 4px 0;
}

</style>